﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.Entity;
using CRM.BLL;
using DP.Web.UI;
using DP.Common;
using DP.Data.OleDb;
using DP.Data.SqlClient;

namespace CRM.Web.CallOutCase
{
    public partial class ImportPage : Common.PageBase
    {
        T_INPUT_LIST_BLL bll = new T_INPUT_LIST_BLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                btnOK.Enabled = false;
                ddlTempNameInit();
                ddlBusinessBinding();
            }
        }

        /// <summary>
        /// 事业部选项加载
        /// </summary>
        private void ddlBusinessBinding()
        {
            string pSql = "";
            T_BUSINESSDIVISION_BLL dal = new T_BUSINESSDIVISION_BLL();
            if (!UserLoginInfo.IsAdministrator())
            {
                pSql = String.Format(" AND BUSINESSDIVISIONCODE = '{0}' ORDER BY BUSINESSDIVISIONNAME", _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE);
                List<T_BUSINESSDIVISION_Entity> list = dal.GetList(pSql);
                ddlBusiness.DataSource = list;
                ddlBusiness.DataTextField = "BUSINESSDIVISIONNAME";
                ddlBusiness.DataValueField = "BUSINESSDIVISIONCODE";
                ddlBusiness.DataBind();
                ddlBusiness.AutoPostBack = true;
            }
            else
            {
                pSql = " AND STATUS = 0 ORDER BY BUSINESSDIVISIONNAME";
                List<T_BUSINESSDIVISION_Entity> list = dal.GetList(pSql);
                ddlBusiness.DataSource = list;
                ddlBusiness.DataTextField = "BUSINESSDIVISIONNAME";
                ddlBusiness.DataValueField = "BUSINESSDIVISIONCODE";
                ddlBusiness.DataBind();
                ddlBusiness.AutoPostBack = true;
                ddlBusiness.Items.Insert(0, new ListItem("全部", ""));
            }
        }

        /// <summary>
        /// Excel文件导入提交操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOK_Click(object sender, EventArgs e)
        {
            #region 输入内容判断

            if (this.lblFullName.Text.Trim() == "")
            {
                PageHelper.ShowMessage(this.Page, "请先上传要导入的文件！");
                return;
            }

            if (this.ddlSheetName.Text.Trim() == "")
            {
                PageHelper.ShowMessage(this.Page, "请选择导入文件的工作表名！");
                return;
            }

            if (this.txtREMARKS.Text.Trim() == "")
            {
                PageHelper.ShowMessage(this.Page, "请输入导入文件描述信息！");
                return;
            }

            //string tempname = ddlTempName.SelectedValue.ToString();
            //if (tempname == "")
            //{
            //    PageHelper.ShowMessage(this.Page, "请选择导入模板！");
            //    return;
            //}

            #endregion

            string strFileName = lblFileName.Text.Trim();
            string strFullName = lblFullName.Text.Trim();
            string strSheetName = ddlSheetName.SelectedItem.Text.TrimEnd('$');

            string sql = String.Format(" AND FILENAME = '{0}' AND SHEETNAME = '{1}'", strFileName, strSheetName);
            DataTable dtRet = bll.GetDataTable(sql);

            if (dtRet.Rows.Count <= 0)
            {
                T_INPUT_LIST_Entity entity = new T_INPUT_LIST_Entity();
                entity.FILENAME = strFileName;
                entity.FILE_PATH = strFullName;
                entity.STATUS = 1;
                entity.SHEETNAME = strSheetName;
                entity.REMARKS = this.txtREMARKS.Text.Trim();
                entity.IF_NAME = this.cbUserName.Checked ? 1 : 0;
                entity.CREATEPEOPLEID = _userLoginInfo.UserEntity.USERID;
                entity.CREATEPEOPLE = _userLoginInfo.UserEntity.USERNAME;
                entity.CREATETIME = DateTime.Now;
                entity.LASTMODIFYPEOPLEID = _userLoginInfo.UserEntity.USERID;
                entity.LASTMODIFYPEOPLE = _userLoginInfo.UserEntity.USERNAME;
                entity.LASTMODIFYTIME = DateTime.Now;
                entity.BUSINESSDIVISIONCODE = ddlBusiness.SelectedValue;
                entity.BUSINESSDIVISIONNAME = ddlBusiness.SelectedItem.Text;

                long rel = bll.Insert(entity);

                if (rel > 0)
                {
                    PageHelper.ShowMessage(this.Page, "已提交至服务器，请稍候查看消息！");
                }
                else
                {
                    PageHelper.ShowMessage(this.Page, "提交失败！请重新提交！");
                }
            }
            else
            {
                PageHelper.ShowMessage(this.Page, "该文件已经导入！");
                return;
            }
        }

        /// <summary>
        /// Excel文件上传操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            String fileExtension = System.IO.Path.GetExtension(ImportFile.FileName).ToLower();
            if (!fileExtension.Equals(".xls"))
            {
                PageHelper.ShowMessage(this.Page, "文件上传类型错误！");
                return;
            }

            string filepath = UploadFile(this.Page, ImportFile);
            string filename = GetFileName(filepath);
            if (string.IsNullOrEmpty(filepath))
            {
                PageHelper.ShowMessage(this.Page, "文件上传失败！");
                return;
            }

            btnOK.Enabled = true;
            lblFullName.Text = filepath;
            lblFileName.Text = GetFileName(ImportFile.PostedFile.FileName);
            ddlSheetNameInit(filepath);
        }

        /// <summary>
        /// 显示Excel文件中的工作表
        /// </summary>
        /// <param name="fileName">Excel文件名</param>
        private void ddlSheetNameInit(string fileName)
        {
            ddlSheetName.DataSource = NPOIExcelHelper.GetSheets(fileName);
            ddlSheetName.DataTextField = "value";
            ddlSheetName.DataValueField = "value";
            ddlSheetName.DataBind();

            //DataView dv = null;

            //OleDbHelper oledbHelper = new OleDbHelper(String.Format(configBll.GetCacheValueByName(this.Page, "OleDbConnStringExcel"), fileName));
            //try
            //{
            //    DataTable dt;
            //    string filename = ImportFile.PostedFile.FileName;
            //    if (filename == "")
            //    {
            //        PageHelper.ShowMessage(this.Page, "请选择需要导入的文件！");
            //        return;
            //    }
            //    dt = oledbHelper.GetSchemaTable();

            //    dv = new DataView(dt, " TABLE_NAME like '%$' ", "", DataViewRowState.CurrentRows);

            //    ddlSheetName.DataSource = dv;
            //    ddlSheetName.DataTextField = "TABLE_NAME";
            //    ddlSheetName.DataValueField = "TABLE_NAME";
            //    ddlSheetName.DataBind();
            //}
            //catch
            //{
            //    ddlSheetName.DataSource = dv;
            //    ddlSheetName.DataTextField = "TABLE_NAME";
            //    ddlSheetName.DataValueField = "TABLE_NAME";
            //    ddlSheetName.DataBind();
            //    PageHelper.ShowMessage(this.Page, "请检查导入的文件类型！");
            //    return;
            //}
        }

        /// <summary>
        /// 填充模板选择列表的内容
        /// </summary>
        private void ddlTempNameInit()
        {
            //string sqlStr = "Select * from crm_input_template ";
            //SqlHelper sqlHelper = new SqlHelper(pmSys.conn_crm);
            //DataTable dt = sqlHelper.ExecuteDataAdapter(CommandType.Text, sqlStr, null).Tables[0];

            //ddlTempName.DataSource = dt;
            //ddlTempName.DataTextField = "template_name";
            //ddlTempName.DataValueField = "template_id";
            //ddlTempName.DataBind();
            //ddlTempName.Items.Insert(0, new ListItem(StaticConstant.DropDownListDefaultText, ""));
        }

        /// <summary>
        /// 文件 上传方法
        /// </summary>
        /// <param name="page">当前页面</param>
        /// <param name="auc">上传控件</param>
        /// <returns>上传后的文件的服务器路径</returns>
        private string UploadFile(Page page, System.Web.UI.WebControls.FileUpload auc)
        {
            string temp = DateTime.Now.ToString("yyyyMMddHHmmss");
            string filename = auc.PostedFile.FileName;
            filename = GetFileName(filename);

            string filepath = HttpContext.Current.Request.MapPath(StaticConstant.UploadFilePath);

            int index = filename.LastIndexOf('.');
            if (index != -1)
            {
                filename = filename.Insert(index, temp);
            }
            else
            {
                filename += temp;
            }

            string fullpath = string.Empty;
            if (filepath.LastIndexOf("\\") == filepath.Length - 1)
            {
                fullpath = filepath + filename;
            }
            else
            {
                fullpath = filepath + "\\" + filename;
            }

            try
            {
                auc.PostedFile.SaveAs(fullpath);
            }
            catch
            {
                fullpath = null;
            }
            return fullpath;
        }

        /// <summary>
        /// 在绝对路径中，获取Excel文件名
        /// </summary>
        /// <param name="input">需要导入的Excel绝对路径</param>
        /// <returns></returns>
        private string GetFileName(string input)
        {
            return input.Substring(input.LastIndexOf("\\") + 1);
        }

        protected void btnAddTemplate_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(lblFullName.Text.Trim()))
            {
                PageHelper.ShowMessage("请要导入的文件！");
                return;
            }

            if (String.IsNullOrEmpty(ddlSheetName.SelectedItem.Text))
            {
                PageHelper.ShowMessage("请先导入的文件的Sheel表！");
                return;
            }

            string fullname = Server.UrlEncode(GetFileName(lblFullName.Text.Trim()));
            string sheelname = Server.UrlEncode(ddlSheetName.SelectedItem.Text.TrimEnd('$')); 

            string url = "CreateNewTemplate.aspx?FileName={0}&SheelName={1}&btnName={2}";
            //PageHelper.ExecuteJS("open('" + String.Format(url, fullname, sheelname, btnReTemplate.ClientID) + "');", this.Page);
        }

        protected void btnReTemplate_Click(object sender, EventArgs e)
        {
            ddlTempNameInit();
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {
            this.ddlTempName.Text = "";
            this.cbUserName.Checked = false;
            this.lblFileName.Text = "";
            this.lblFullName.Text = "";
            this.ddlSheetName.Text = "";
            this.txtREMARKS.Text = "";
        }
    }
}
